package com.server;

import java.nio.charset.Charset;

import org.apache.log4j.Logger;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoderAdapter;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

import com.gateway.core.MyBuffer;
import com.gateway.core.MyProtocol;

public class MyLogicServerProtocolDecoder extends ProtocolDecoderAdapter {
  
  private Logger log=Logger.getLogger(this.getClass());

  @SuppressWarnings("unused")
  private Charset charset;

  public MyLogicServerProtocolDecoder(Charset charset) {
    this.charset=charset;
  }

  /**
   * 对网关解码
   */
  public void decode(IoSession session, IoBuffer buffer, ProtocolDecoderOutput out) throws Exception {
    MyBuffer myBuf=new MyBuffer(buffer);
    byte type=myBuf.get();
    int bodyLength=myBuf.getInt();
    if(myBuf.remaining() >= bodyLength) {
      // 解析出协议体部分
      byte[] body=new byte[bodyLength];
      myBuf.get(body);
      MyBuffer bodyBuf=MyBuffer.allocate(bodyLength);
      bodyBuf.put(body);
      bodyBuf.flip();
      // 封装成MyProtocol
      MyProtocol myProtocol=new MyProtocol(type, bodyBuf.getIoBuffer());
      out.write(myProtocol);
    } else {
      log.debug("数据有问题");
      return;
    }
  }
}
